package main.java.indi.zyj.sword;

import main.java.indi.zyj.hot100.base.TreeNode;

import java.util.HashMap;
import java.util.Map;

public class DeduceTree {

    Map<Integer, Integer> inMap;

    public TreeNode deduceTree(int[] preorder, int[] inorder) {

        inMap = new HashMap<>();

        for (int i = 0; i < inorder.length; i++) {
            inMap.put(inorder[i], i);
        }

        return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length);

    }

    private TreeNode buildTree(int[] preorder, int preorder_left, int preorder_right, int[] inorder, int inorder_left, int inorder_right) {

        if (preorder_left > preorder_right) {
            return null;
        }

        int rootVal = preorder[preorder_left];

        int inorderRootIndex = inMap.get(rootVal);

        int len = inorderRootIndex - inorder_left;

        TreeNode root = new TreeNode(rootVal);

        root.left = buildTree(preorder, preorder_left + 1, preorder_left + len, inorder, inorder_left, inorderRootIndex - 1);
        root.right = buildTree(preorder, preorder_left + 1 + len, preorder_right, inorder, inorderRootIndex + 1, inorder_right);

        return root;

    }

}
